import io from 'socket.io-client'
import vue from '../../main';
import { Notification } from 'element-ui'
/* eslint-disable */
const socketURL = 'http://47.101.45.245:8878' || 'http://localhost:8878';
const socket = io.connect(socketURL);

let remoteUser = localStorage.getItem('doctor_id'); // 远端用户
let localUser = ''; // 本地登录用户

socket.on('connect', () => {
    // 连接
    socket.emit('join', {userid: localStorage.getItem('doctor_id')})
})

// 监听问诊消息
socket.on('inquiry', (msg) => {
    msg = JSON.parse(msg);
    vue.$store.commit('doctorStore/pushMessage', msg);
    Notification({
        title: '消息',
        message: msg.message.type === 1 ? msg.message.content: '您有新的消息',
        type: 'success'
      });
})

// 监听ocr情况
socket.on('CLIENT_OCR_NONE',(msg) => {
    console.log('dont found ',msg);
    msg = JSON.parse(msg);
    let context = msg.words_result.map(item => item.words).join(';');
    Notification({
        title: 'OCR识别到以下文本',
        message: context || '未识别有效信息',
        type: 'success',
        duration: 0
    });
})

// 监听ocr结果
socket.on('CLIENT_OCR',(msg) => {
    console.log('data fount ',msg);
    msg = JSON.parse(msg);
    let html = `
    <div>
    <h3>主诉: </h3><p>${msg.chiefComplaint}</p>
    <h3>体格检查: </h3><p>${msg.physicalExamination}</p>
    <h3>辅助检查: </h3><p>${msg.supplementaryExamination}</p>
    <h3>诊断结果: </h3><p>${msg.diagnosis}</p>
    </div>
    `
    Notification({
        title: '找到类似病历',
        dangerouslyUseHTMLString: true,
        message: html,
        type: 'info',
        duration: 0
    });
})

socket.on('reconnect', () => {
    console.log('socket 重新连接')
    socket.emit('join', {userid: localStorage.getItem('doctor_id')})
})

socket.on('connection_error' , (errorMessage) => {
    // 连接异常
})

socket.on('error', (errorMessage) => {
    // socket异常
})

socket.on('SERVER_USER_EVENT', (msg) => {
    // 服务器用户事件
    const {type, payload} = msg;

    switch(type) {
        case 'SERVE_USER_EVENT_UPDATE_USER':
        break;
        default:
        break;
    }
})

socket.on('SERVE_RTC_EVENT', (msg) => {
    // 服务器webrct事件
    const {type} = msg;

    switch(type) {
        case 'SIGNALING_OFFER':
            handleReceiveOffer(msg);
            break;
        case 'SIGNALING_ANSWER':
            handleReceiveAnswer(msg);
            break;
        case 'SIGNALING_CANDIDATE':
            handleReceiveCandidate(msg);
            break;
        case 'CLOSE':
            console.log('通知close')
            stopVideoTalk(msg);
    }
});

/**
 * 发送RTC相关消息给服务器
 * @param {Object} msg 格式如:{type: 'xx', payload: {}}
 */
function sendRTCEvent(msg) {
    socket.emit('CLIENT_RTC_EVENT', JSON.stringify(msg));
}

async function handleReceiveOffer(msg) {
    
    // 设置远端描述
    const remoteDescription = new RTCSessionDescription(msg.payload.sdp);
    remoteUser = msg.payload.from;
    // 创建连接
    createPeerConnection();
    await pc.setRemoteDescription(remoteDescription); // 错误处理

    // 本地音视频采集
    const localVideo = document.getElementById('local-video');
    mediaStream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true,
    })
    localVideo.srcObject = mediaStream;
    mediaStream.getTracks().forEach(track => {
        pc.addTrack(track, mediaStream);
    });

    const answer = await pc.createAnswer(); // TODO 错误处理
    await pc.setLocalDescription(answer);
    // 发送消息， 后期需处理格式
    sendRTCEvent({
        type: 'SIGNALING_ANSWER',
        payload: {
            sdp: answer,
            from: localUser,
            target: remoteUser,
        }
    })
}

async function handleReceiveAnswer(msg) {

    const remoteDescription = new RTCSessionDescription(msg.payload.sdp);
    remoteUser = msg.payload.from;

    await pc.setRemoteDescription(remoteDescription); //TODO 错误处理
}

async function handleReceiveCandidate(msg) {
    await pc.addIceCandidate(msg.payload.candidate); // TODO 错误处理
}

let pc = null;
let mediaStream = null;
/**
 * 邀请用户加入视频聊天
 *  1、本地启动视频采集
 *  2、交换信令
 */
export async function startVideoTalk(remoteid) {
    remoteUser = remoteid;
    if (remoteUser.length <= 0) return;
    console.log('remoteUser is ', remoteid, remoteUser)
    // 开启本地视频 - 适配
    // var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
    const localVideo = document.getElementById('local-video');
    mediaStream = await navigator.mediaDevices.getUserMedia({
        video: true, 
        audio: true
    });
    localVideo.srcObject = mediaStream;
    localVideo.onloadedmetadata = function (e) {
        console.log("Label: " + mediaStream.label);
        console.log("AudioTracks", mediaStream.getAudioTracks());
        console.log("VideoTracks", mediaStream.getVideoTracks());
    };
    // 创建 peerConnection
    createPeerConnection();
    // 将媒体流添加到webrtc的音视频收发器
    mediaStream.getTracks().forEach(track => {
        pc.addTrack(track, mediaStream);
        track.stop();
        // pc.addTransceiver(track, {streams: [mediaStream]});
    });
    // pc.addStream(mediaStream); // 目前这个也可以，不过接口后续会废弃
}

export const onFallEvent = {

}

export function stopVideoTalk(msg) {
    mediaStream.getVideoTracks().map(track => {
        track.stop();
    })
    mediaStream.getAudioTracks().map(track => {
        track.stop();
    })
    if (!msg) {
        // 发送socket通知对方关闭音频流
        sendRTCEvent({
            type: 'CLOSE',
            payload: {
                from: localStorage.getItem('doctor_id'),
                target: remoteUser,
            }
        })
    } else {
        console.log(onFallEvent);
        if (typeof onFallEvent.onClose === 'function') {
            onFallEvent.onClose(msg);
        }
    }
}

function createPeerConnection() {
    const iceConfig = {"iceServers": [
        {url: 'stun:stun.ekiga.net'},
        {url: 'turn:turnserver.com', username: 'user', credential: 'pass'}
    ]};
    
    pc = new RTCPeerConnection(iceConfig);

    pc.onnegotiationneeded = onnegotiationneeded;
    pc.onicecandidate = onicecandidate;
    pc.ontrack = ontrack;
    
    return pc;
}

async function onnegotiationneeded() {

    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer); // TODO 错误处理

    sendRTCEvent({
        type: 'SIGNALING_OFFER',
        payload: {
            from: localStorage.getItem('doctor_id'),
            target: remoteUser,
            sdp: pc.localDescription // TODO 直接用offer？
        }
    });
}

function onicecandidate(evt) {
    if (evt.candidate) {

        sendRTCEvent({
            type: 'SIGNALING_CANDIDATE',            
            payload: {
                from: localStorage.getItem('doctor_id'),
                target: remoteUser,
                candidate: evt.candidate
            }
        });
    }
}


let stream;
function ontrack(evt) {
    // if (!stream) {
    //     stream = evt.streams[0];
    // } else {
    //     console.log(`${stream === evt.streams[0]}`); // 这里为true
    // }
    document.getElementById('video-div').className="show";
    const remoteVideo = document.getElementById('remote-video');
    remoteVideo.srcObject = evt.streams[0];
}
/* eslint-disable */

export default socket